#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GoUserAgent 测试运行器
用于运行指定的Go测试集合，避免内存问题
"""

import subprocess
import os
import sys
import time

# 项目根目录
PROJECT_DIR = r"d:\Code\gitee\go\GoUserAgent"

# 测试集合
test_cases = [
    "TestModelBrandRestriction",
    "TestBrandOSRestriction", 
    "TestGenerateWithOptions",
    "TestMobileUA",
    "TestDesktopUA"
]

def run_test(test_name):
    """运行单个测试"""
    cmd = ["go", "test", "-v", f"-run={test_name}"]
    print(f"\n{'='*60}")
    print(f"运行测试: {test_name}")
    print(f"命令: {' '.join(cmd)}")
    print('='*60)
    
    try:
        result = subprocess.run(
            cmd,
            cwd=PROJECT_DIR,
            capture_output=True,
            text=True,
            timeout=30,
            encoding='utf-8',
            errors='ignore'
        )
        
        if result.returncode == 0:
            print(f"✅ {test_name} 测试通过")
            if result.stdout:
                lines = result.stdout.strip().split('\n')
                for line in lines[-5:]:  # 只显示最后5行
                    if line.strip():
                        print(f"  {line}")
        else:
            print(f"❌ {test_name} 测试失败")
            if result.stderr:
                print("错误信息:")
                print(result.stderr)
                
        return result.returncode == 0
        
    except subprocess.TimeoutExpired:
        print(f"⏰ {test_name} 测试超时")
        return False
    except Exception as e:
        print(f"💥 {test_name} 运行异常: {e}")
        return False

def main():
    """主函数"""
    print("🚀 GoUserAgent 测试运行器启动")
    print(f"项目目录: {PROJECT_DIR}")
    
    # 检查go.mod是否存在
    go_mod_path = os.path.join(PROJECT_DIR, "go.mod")
    if not os.path.exists(go_mod_path):
        print("❌ 未找到go.mod文件，请检查项目路径")
        sys.exit(1)
    
    # 运行测试
    passed = 0
    failed = 0
    
    start_time = time.time()
    
    for test_name in test_cases:
        if run_test(test_name):
            passed += 1
        else:
            failed += 1
    
    end_time = time.time()
    
    # 总结
    print(f"\n{'='*60}")
    print("📊 测试总结")
    print('='*60)
    print(f"总测试数: {len(test_cases)}")
    print(f"通过: {passed}")
    print(f"失败: {failed}")
    print(f"耗时: {end_time - start_time:.2f}秒")
    
    if failed == 0:
        print("🎉 所有测试通过!")
        return 0
    else:
        print("⚠️  部分测试失败")
        return 1

if __name__ == "__main__":
    sys.exit(main())